package com.yc.distribute.lock;

import java.util.concurrent.CountDownLatch;

import com.yc.distribute.lock.zookeeper.ZookeeperLock;

public class Test {
	ZookeeperLock lock = null;
	
	public Test() {
		try {
			lock = new ZookeeperLock("/yc/test1");
			System.out.println("lock创建完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	CountDownLatch cdl = new CountDownLatch(10);
	int count = 0;
	
	/**
	 * 多线程操作
	 */
	public void testMultiThread() {
		System.out.println("启动10个线程");
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				for (int j = 0; j < 5; j++) {
//					operaCount();
					operaCount_zk();
				}
				cdl.countDown();
			}).start();
		}
		
		System.out.println("等待10个线程跑完");
		try {
			cdl.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		//输出结果：正确值：0
		System.out.println("count =" + count);
	}
	
	
	private void operaCount() {
		count++;
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		count--;
	}
	
	public synchronized void operaCount_zk() {
		System.out.println(Thread.currentThread().getName());
		try {
			lock.lock();
			
			count++;
			Thread.sleep(1000);
			count--;
			
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			lock.unlock();
		}
		
	}

	public static void main(String[] args) {
		Test t = new Test();
		t.testMultiThread();//最终结果错误
//		t.operaCount_zk();
	}

}
